package com.lzx.iteam.net;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.lzx.iteam.LoginActivity;
import com.lzx.iteam.MainActivity;
import com.lzx.iteam.R;
import com.lzx.iteam.SettingActivity;
import com.lzx.iteam.bean.EventListData;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.PreferenceUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Megan on 15/11/4.
 */
public class EventListCenter {

    private static final String TAG = "get_event_data";
    private static final int MSG_EVENT_GET_LIST = 1000;
    private EventDataListener mListener;
    private CloudDBOperation mCloudDBOperation;
    private static EventListCenter sInstance;
    private PreferenceUtil mPreferenceUtil;
    private Context mContext;
//    private boolean isUpDate;
    private int mPageIndex;
    private AllDialogUtil mDialogUtil;
    private String mType = "0";//事件类型 0. 全部, 1：公告，2：审批，3：周报，4：普通事件，5：自定义  6:系统通知  7：活动 8：投票
    private ArrayList<EventListData> mEventListDatas = new ArrayList<EventListData>();

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_EVENT_GET_LIST:
                    if (msg.arg1 == 0) {
                        notifyEventList();
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            /*Toast.makeText(mContext, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();*/
                        } else if (msg.arg1 == 1002 || msg.arg1 == 1003 ) {//其他接口也应该加此判断，当前其他接口未加
                            mDialogUtil.titleMsgBtnStyle("提示", (String) msg.obj, mContext.getString(R.string.ok));
                            mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

                                @Override
                                public void onConfirmClick(Dialog lDialog) {

                                    lDialog.dismiss();
                                    Intent intent = new Intent(mContext, LoginActivity.class);
                                    mContext.startActivity(intent);
                                    ((MainActivity)mContext).finish();

                                }

                                @Override
                                public void onCancelClick(Dialog lDialog) {
                                }
                            });
                        } else {
                            if (mListener != null) mListener.onError(msg.arg1, (String) msg.obj);
                        }
                    }
                    break;
            }

        }
    };


    private EventListCenter(Context context) {
        mContext = context;
        mCloudDBOperation = new CloudDBOperation(context);
        mPreferenceUtil = PreferenceUtil.getInstance(mContext);
        mDialogUtil = AllDialogUtil.getInstance((Activity)mContext);
    }

    public static EventListCenter getInstance(Context c) {
        if (sInstance == null) {
            sInstance = new EventListCenter(c);
        }
        return sInstance;
    }


    public interface EventDataListener {
        void onChange(ArrayList<EventListData> eventList);

        void onNoChange(ArrayList<EventListData> eventList);

        void onAddMore(ArrayList<EventListData> eventList);

        void onError(int errNum, String obj);
    }

    public void setUpdateEventListener(EventDataListener listener) {
        this.mListener = listener;
    }

    public ArrayList<EventListData> getEventData(int pageIndex, int type) {
//        this.isUpDate = update;
        this.mPageIndex = pageIndex;
        this.mType = type + "";
        mEventListDatas.clear();
        mEventListDatas = mCloudDBOperation.findEventsByType(mType);
//        mEventListDatas = mCloudDBOperation.findEventsByType(mType, 1, pageIndex * 10);
//        StringBuilder sb = new StringBuilder();
//        int l = 0;
//        if (mEventListDatas.size() > 10) {
//            l = mEventListDatas.size()-10;
//        } else {
//            l = 0;
//        }
//        for (int i = mEventListDatas.size()-1; i >=l; i--) {
//            sb.append(mEventListDatas.get(i).getEventId());
//            if (i != l) {
//                sb.append(",");
//            }
//        }
        getEventsList(mType, pageIndex);
//        getEventsList(mType, pageIndex,sb.toString());
        return mEventListDatas;
    }

    private EventListData removeEventById(String eventId, ArrayList<EventListData> localEventData) {

        for (int i = 0; i < localEventData.size(); i++) {
            if (localEventData.get(i).getEventId().equals(eventId)) {
                return localEventData.remove(i);
            }
        }
        return null;
    }

    public void eraseEventData() {
        /*mContext.getContentResolver().delete(CloudGroupDbo.CONTENT_URI, null, null);*/
        mCloudDBOperation.deleteAllEvents();
//        notifyEventList();
    }



    /**
     * 获取事件列表
     *
     * @param type 事件类型 0. 全部, 1：公告，4：普通事件， 6:系统事件  7：活动 8：投票 9:签到
     */
    public void getEventsList(String type, int pageIndex) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_TYPE, type));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, pageIndex * 10 + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, "1"));
        /*if (isUpDate) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, pageIndex * 10 + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, "1"));
        } else {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, "10"));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, pageIndex + ""));
        }*/
        EventDataMessage.GetEventListData eventListData = new EventDataMessage.GetEventListData(mHandler.obtainMessage(MSG_EVENT_GET_LIST), mContext, type,pageIndex);
        eventListData.mApi = AsynHttpClient.API_EVENT_LIST_V3;
        eventListData.mParams = nvps;
        AsynHttpClient.getInstance(mContext).execEventHttp(eventListData);
    }

    /**
     * 获取事件列表
     *
     * @param type 事件类型 0. 全部, 1：公告，4：普通事件， 6:系统事件  7：活动 8：投票 9:签到
     * @param update     true: 刷新数据   false：分页增加数据
     */
    public void getEventsList(String type, int pageIndex, boolean update) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_TYPE, type));
        if (update) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, pageIndex * 10 + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, "1"));
        } else {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, "10"));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, pageIndex + ""));
        }
        EventDataMessage.GetEventListData eventListData = new EventDataMessage.GetEventListData(mHandler.obtainMessage(MSG_EVENT_GET_LIST), mContext, type,pageIndex);
        eventListData.mApi = AsynHttpClient.API_EVENT_LIST_V3;
        eventListData.mParams = nvps;
        AsynHttpClient.getInstance(mContext).execEventHttp(eventListData);
    }

    /**
     * 此方法会对比本地查询的结果和从服务器获取的结果
     * 如果本地不存在，则将获取的结果存入数据库
     * 如果本地已经存在的数据中包含从服务器段获取的，则更新数据库(并删除本地的这个数据)
     * 本地和获取的匹配完毕之后，若本地的变量还有数据，则将剩下的数据从数据库中全部删除
     *
     * @param localEventList
     * @param cloudEventList
     * @return
     */
    private boolean updateCloudEventData(ArrayList<EventListData> localEventList, ArrayList<EventListData> cloudEventList) {
        boolean needUpdate = false;

        //如果本地没有，则将从服务器获取的插入数据库，成功则返回true
        if (localEventList.size() == 0) {
            for (int i = 0; i < cloudEventList.size(); i++) {
                needUpdate |= (mCloudDBOperation.insertEvent(cloudEventList.get(i)) != 0);
            }
            return needUpdate;
        }
        //如果本地有
        Iterator<EventListData> i = cloudEventList.iterator();
        while (i.hasNext()) {
            EventListData cloudItem = i.next();
            i.remove();
            //如果本地的里面包含从服务器获取的，则将本地里面的删除掉
            EventListData localItem = removeEventById(cloudItem.getEventId(), localEventList);
            //如果不包含，则添加进数据库
            if (localItem == null) {
                needUpdate |= (mCloudDBOperation.insertEvent(cloudItem) != 0);
                continue;
            }
            //如果包含，且更新时间新于本地的，则更新数据库里的
            if (!cloudItem.getUpdateTime().equals(localItem.getUpdateTime())) {
                needUpdate |= (mCloudDBOperation.updateEventData(cloudItem.getEventId(), cloudItem) != 0);
                continue;
            }
        }
        //如果服务器获取到的匹配完毕，本地还有的话，则删除数据库中的本地剩下的过时数据
        if (localEventList.size() > 0) {
            deleteEventData(localEventList);
            needUpdate = true;
        }
        return needUpdate;
    }


    private void deleteEventData(ArrayList<EventListData> eventList) {
        if (eventList == null || eventList.size() == 0) {
            Log.w(TAG, "deleteCloudGroupItem with null group list.");
        }

        for (int i = 0; i < eventList.size(); i++) {
            mCloudDBOperation.deleteEventByEventId(eventList.get(i).getEventId());
            Log.i(TAG, "--delete_event Id--" + eventList.get(i).getEventId());
        }

    }

    private void notifyEventList(){
//        mEventListDatas = mCloudDBOperation.findEventsByType(mType, 1, mPageIndex * 10);
        mEventListDatas = mCloudDBOperation.findEventsByType(mType);
        if (mListener != null) mListener.onChange(mEventListDatas);
    }


}
